// index.ts
// 获取应用实例
const { bannerList, goodList, getUser, getCode, noticeDialog, openMini } = require('../../utils/api.js')
const app = getApp()
var lastFrameTime = 0;
var count = 0;
var ctx = null;
var factor = {
  speed: .008, // 运动速度，值越小越慢
  t: 0 //  贝塞尔函数系数
};
var that;
var timer = null; // 循环定时器
Page({
  data: {
    swiperList: [],
    userInfo: {},
    pointList: [],
    isJwt: false,  //是否登录 false  没登录  true 登录
    showLogin: false,
    fatherData: {},
    showModal: false, //扫描成功弹窗
    showErrModal: false,
    errData: '',
    page: 1,
    limit: 10,
    count: null,
    onBottom: false,
    noticeList: [],
    showRule: false,
    ruleMsg: {},
    myData: '',
    showStar: false,
    img_path: [
      [{
        x: 200,
        y: 400
      }, {
        x: 70,
        y: 300
      }, {
        x: -50,
        y: 150
      }, {
        x: 200,
        y: 0
      }],
      [{
        x: 200,
        y: 400
      }, {
        x: 30,
        y: 300
      }, {
        x: 80,
        y: 150
      }, {
        x: 200,
        y: 0
      }],
      [{
        x: 200,
        y: 400
      }, {
        x: 0,
        y: 90
      }, {
        x: 80,
        y: 100
      }, {
        x: 200,
        y: 0
      }]
    ],
    showCanvas: false
  },

  onLoad(options) {
    let that = this
    //分享获取上级id 
    if (options && options.shangjiuid) {
      wx.setStorageSync('shangjiuid', options.shangjiuid);
      wx.setStorageSync('create_mode', 2)
    }

    //获取二维码数据
    if (app.globalData.qrCode) {
      that.getCodeMsg(app.globalData.qrCode)
      wx.setStorageSync('create_mode', 1)
    }

    that.getNotice()
    ctx = wx.createCanvasContext('mycanvas')
  },


  requestAnimationFrame(callback) {
    var currTime = new Date().getTime();
    //手机屏幕刷新率一般为60Hz，大概16ms刷新一次，这里为了使页面看上去更流畅自然,通过改变timedis的值可以控制动画的快慢
    var timedis = 16 - (currTime - lastFrameTime)
    var timeToCall = Math.max(0, timedis);
    var id = setTimeout(callback, timeToCall);
    lastFrameTime = currTime + timeToCall;
    return id;
  },


  drawImage: function (data, repeatcount) {
    let that = this
    if (repeatcount == 0) {
      return
    }
    var p10 = data[0][0]; // 三阶贝塞尔曲线起点坐标值
    var p11 = data[0][1]; // 三阶贝塞尔曲线第一个控制点坐标值
    var p12 = data[0][2]; // 三阶贝塞尔曲线第二个控制点坐标值
    var p13 = data[0][3]; // 三阶贝塞尔曲线终点坐标值

    var p20 = data[1][0];
    var p21 = data[1][1];
    var p22 = data[1][2];
    var p23 = data[1][3];

    var p30 = data[2][0];
    var p31 = data[2][1];
    var p32 = data[2][2];
    var p33 = data[2][3];

    var t = factor.t;

    /*计算多项式系数*/
    var cx1 = 3 * (p11.x - p10.x);
    var bx1 = 3 * (p12.x - p11.x) - cx1;
    var ax1 = p13.x - p10.x - cx1 - bx1;

    var cy1 = 3 * (p11.y - p10.y);
    var by1 = 3 * (p12.y - p11.y) - cy1;
    var ay1 = p13.y - p10.y - cy1 - by1;

    /*计算xt yt坐标值 */
    var xt1 = ax1 * (t * t * t) + bx1 * (t * t) + cx1 * t + p10.x;
    var yt1 = ay1 * (t * t * t) + by1 * (t * t) + cy1 * t + p10.y;

    /** 计算多项式系数*/
    var cx2 = 3 * (p21.x - p20.x);
    var bx2 = 3 * (p22.x - p21.x) - cx2;
    var ax2 = p23.x - p20.x - cx2 - bx2;

    var cy2 = 3 * (p21.y - p20.y);
    var by2 = 3 * (p22.y - p21.y) - cy2;
    var ay2 = p23.y - p20.y - cy2 - by2;

    /*计算xt yt坐标值*/
    var xt2 = ax2 * (t * t * t) + bx2 * (t * t) + cx2 * t + p20.x;
    var yt2 = ay2 * (t * t * t) + by2 * (t * t) + cy2 * t + p20.y;


    /** 计算多项式系数*/
    var cx3 = 3 * (p31.x - p30.x);
    var bx3 = 3 * (p32.x - p31.x) - cx3;
    var ax3 = p33.x - p30.x - cx3 - bx3;

    var cy3 = 3 * (p31.y - p30.y);
    var by3 = 3 * (p32.y - p31.y) - cy3;
    var ay3 = p33.y - p30.y - cy3 - by3;

    /*计算xt yt坐标值*/
    var xt3 = ax3 * (t * t * t) + bx3 * (t * t) + cx3 * t + p30.x;
    var yt3 = ay3 * (t * t * t) + by3 * (t * t) + cy3 * t + p30.y;
    factor.t += factor.speed;
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", xt1, yt1, 32, 36);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", xt2, yt2, 34, 38);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", xt3, yt3, 38, 40);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 200, yt2, 28, 32);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 300, xt1, 28, 32);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 201, yt3, 40, 44);
    ctx.draw();
    if (factor.t > 1) {
      factor.t = 0;
      clearTimeout(timer)
      if (repeatcount <= -1) {
        that.startTimer(repeatcount)
      } else {
        if (count < repeatcount) {
          that.startTimer(repeatcount)
          count++
        } else {
          that.draworiginal()
          count = 0;
        }
      }
    } else {
      timer = that.requestAnimationFrame(function () {
        that.drawImage(that.data.img_path, repeatcount)
      })
    }
  },

  startTimer: function (repeatcount) {
    this.drawImage(this.data.img_path, repeatcount)
  },
  draworiginal() {
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 30, 400, 30, 30);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 30, 400, 30, 30);
    ctx.drawImage("../../static/taskimg/jifen-light-icon.png", 30, 400, 30, 30);
    ctx.draw();
  },


  showStarFun() {
    let that = this
    that.setData({
      showStar: true
    })
    setTimeout(function () {
      that.setData({
        showStar: false,
        showCanvas: true

      })
      factor.t = 2
      count = 0
      that.startTimer(1)
    }, 500);
    setTimeout(function () {
      that.setData({
        showCanvas: false
      })
    }, 3000);
  },

  onShow() {
    let that = this
    var pages = getCurrentPages();
    var currPage = pages[pages.length - 1];
    this.data.myData = currPage.data.preData

    if (this.data.myData) {
      let resStr = this.data.myData
      let strIndex = resStr.indexOf('goodsurl=') + 9
      let resParams = resStr.substr(strIndex)
      this.getCodeMsg(resParams)

    }


    this.setData({
      page: 1
    })
    wx.pageScrollTo({
      scrollTop: 0,
      duration: 300,
    })


    if (typeof this.getTabBar === 'function' &&
      that.getTabBar()) {
      that.getTabBar().setData({
        selected: 0,
      })

    }

    that.getBanner() //轮播图
    that.getGoodsList() //商品列表
    that.getPageData() //页面数据

  },


  onReady() {
    let that = this
    const jwt = wx.getStorageSync('jwt');
    if (jwt) {
      openMini().then((res) => {

      })
    } else {
      return
    }


  },

  getPageData() {
    let that = this
    const jwt = wx.getStorageSync('jwt');
    if (jwt) {
      that.setData({
        isJwt: true
      })
    } else {
      that.setData({
        isJwt: false
      })
    }

    if (that.data.isJwt) {
      that.getUserInfo()
    }

  },

  async getNotice() {
    await noticeDialog().then((res) => {
      this.setData({
        noticeList: res.data.notices,

      })
      this.data.noticeList.map((item) => {
        this.setData({
          "ruleMsg.title": item.title,
          "ruleMsg.content": item.content,
          "ruleMsg.type": item.type //0 文字 1 图片
        })
      })
      if (this.data.noticeList.length != 0) {
        this.setData({
          showRule: true
        })
      }
    })
  },

  //获取商品列表
  async getGoodsList() {
    let params = {
      page: this.data.page,
      limit: this.data.limit
    }
    await goodList(params).then((res) => {

      if (res.errcode == 0) {
        if (this.data.onBottom == false) {
          this.setData({
            count: res.data.goodslist.count,
            pointList: res.data.goodslist.goods
          })
        } else {
          let newArr = [...this.data.pointList, ...res.data.goodslist.goods]
          this.setData({
            pointList: newArr
          })
        }


      } else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
        });
      }
    })

  },

  async getUserInfo() {
    let that = this
    await getUser().then((res) => {

      if (res.errcode == 0) {
        that.setData({
          userInfo: res.user
        })

      }
      else {
        wx.showToast({
          title: res.errmsg,
          icon: 'none',
          success: (result) => {
            setTimeout(() => {
              wx.clearStorage({
                success: function (res) {
                  that.setData({
                    isJwt: false
                  })
                }
              })

            }, 1000);

          },
        });

      }

    })
  },


  //商品详情
  onDetail(e) {
    wx.navigateTo({ url: `/packageA/pages/goodsdetail/index?goodsid=${e.currentTarget.dataset.item.id}` })
  },

  //跳转积分页面
  onPointPage() {
    wx.navigateTo({ url: '/packageA/pages/pointpage/index' })
  },

  onLogin() {
    let that = this
    that.setData({
      showLogin: true
    })

  },

  //获取二维码数据
  async getCodeMsg(url) {
    let that = this
    let params = {
      goodsurl: url
    }
    await getCode(params).then((res) => {
      if (res.errcode == 0) {
        that.setData({
          showModal: true,
          fatherData: res.data,
          "fatherData.numRes": res.data.canscore * Number(res.data.multiplier),
          "fatherData.nexttime": (res.data.nexttime).substring(0, 10),
          "fatherData.endtime": (res.data.endtime).substring(0, 10),
          "fatherData.goodsurl": url,

        })

        var pages = getCurrentPages();
        var currPage = pages[pages.length - 1];
        currPage.setData({
          preData: ''
        })

        app.globalData.qrCode = ''

      } else {
        that.setData({
          showErrModal: true,
          errData: res.errmsg,
        })
        var pages = getCurrentPages();
        var currPage = pages[pages.length - 1];
        currPage.setData({
          preData: ''
        })
        app.globalData.qrCode = ''

      }
    })
  },
  //扫码方法
  getScanCode() {
    wx.navigateTo({
      url: '/component/camerapage/index',
    });
    // let that = this
    // wx.scanCode({
    //   success(res) {
    //     if (res.result) {
    //       let resStr = res.result
    //       let strIndex = resStr.indexOf('goodsurl=') + 9
    //       let resParams = resStr.substr(strIndex)
    //       that.getCodeMsg(resParams)
    //     }
    //   }
    // })
  },

  //获取轮播图
  async getBanner() {
    await bannerList().then((res) => {
      if (res.errcode == 0) {
        this.setData({
          swiperList: res.data.banners
        })
      }
    })
  },

  //点击轮播图 
  onSwiperImg(e) {
    wx.navigateTo({
      url: `/packageA/pages/bannerpage/index?src=${e.currentTarget.dataset.item.jump_url}`,
    });
  },

  //邀请
  onInvitation() {
    let that = this
    if (!that.data.isJwt) {
      that.setData({
        showLogin: true
      })
    } else {
      wx.navigateTo({ url: '/packageA/pages/sharepage/index' })
    }


  },

  //签到
  onSignin() {

    let that = this
    if (!that.data.isJwt) {
      that.setData({
        showLogin: true
      })
    } else {
      wx.navigateTo({ url: '/pages/signinpage/index' })
    }


  },

  //视频号
  onVideo() {
    wx.openChannelsUserProfile({
      finderUserName: 'sphTZV76ORCCG2y'
    })
  },

  //加载
  onReachBottom() {
    if (this.data.page * this.data.limit >= this.data.count) {
      this.setData({
        onBottom: false
      })
      wx.showToast({
        title: '没有更多了',
        icon: 'none',

      });

    } else {
      this.setData({
        onBottom: true
      })
      this.data.page++
      this.getGoodsList()
    }

  },
  onUnload: function () {
    if (timer != null) {
      clearTimeout(timer)
    }

  },

})
